﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

using LowLevelGraphics;
using LowLevelGraphics.Filter;

namespace ImageRecognition2.Action
{
    /// <summary>
    /// Action Color Distance
    /// </summary>
    public class ActionColorDistance : AbstractCommand
    {
        protected Color m_Color = Color.Transparent;
        protected Color m_MinColor = Color.Transparent;
        protected Color m_MaxColor = Color.Transparent;

        protected Color m_MarkerColor = Definitions.Red;

        public ActionColorDistance(Color _color)
        {
            m_Color = _color;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="_actionColorDistance"></param>
        internal ActionColorDistance(ActionColorDistance _actionColorDistance)
        {
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void Run(object sender, EventArgs e)
        {
            int nDistanceMin = int.MaxValue;
            int nDistanceMax = int.MinValue;
            Bitmap bitmap = (Bitmap)MainFormSingleton.ActivePictureBox.BackgroundImage;

            PerPixelFilter perPixelFilter = new PerPixelFilter(new PerPixelFilter.PerPixelFilterDelegate(
                delegate(Color _color)
                {
                    int nDistanceTempMin = ColorFunctions.DistanceSquared(m_Color, _color);
                    int nDistanceTempMax = nDistanceTempMin;
                    if (nDistanceTempMin < nDistanceMin)
                    {
                        nDistanceMin = nDistanceTempMin;
                        m_MinColor = _color;
                    }
                    if (nDistanceTempMax > nDistanceMax)
                    {
                        nDistanceMax = nDistanceTempMax;
                        m_MaxColor = _color;
                    }
                    return _color; 
                }));

            PerPixelFilter perPixelFilterRecolor = new PerPixelFilter(new PerPixelFilter.PerPixelFilterDelegate(
                delegate(Color _color)
                {
                    if (_color == m_MinColor)
                    {
                        _color = m_MarkerColor;
                    }
                    return _color;
                }
            ));

            perPixelFilter.Execute(bitmap).Dispose();
            perPixelFilterRecolor.Execute(bitmap).Dispose();
            MainFormSingleton.ActivePictureBox.Invalidate();
        }

        public Color MaxColor
        {
            get { return m_MaxColor; }
        }

        public Color MinColor
        {
            get { return m_MinColor; }
        }

        public override object Clone()
        {
            return new ActionColorDistance(this);
        }
    }

}
